package org.chl.chapter05.dao;

import java.util.List;

import javax.annotation.Resource;

import org.chl.chapter05.model.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class BookDao {
	// 写连接
    @Resource(name = "jdbcTemplateOne")
    JdbcTemplate jdbcTemplateOne;
    
    // 读连接
    @Autowired
    @Qualifier("jdbcTemplateTwo")
    JdbcTemplate jdbcTemplateTwo;

	public int addBook(Book book) {
		return jdbcTemplateOne.update("INSERT INTO book(name , author) VALUES (? , ?) ", book.getName(), book.getAuthor());
	}

	public int updateBook(Book book) {
		return jdbcTemplateOne.update("UPDATE book SET name=?,author=? WHERE id=?", book.getName(), book.getAuthor(),
				book.getId());
	}

	public int deleteBookByid(Integer id) {
		return jdbcTemplateOne.update(" DELETE FROM book WHERE id=?", id);
	}

	public Book getBookByid(Integer id) {
		return jdbcTemplateTwo.queryForObject("select * from book where id=?", new BeanPropertyRowMapper<>(Book.class),
				id);
	}

	public List<Book> getAllBooks() {
		return jdbcTemplateTwo.query("select * from book", new BeanPropertyRowMapper<>(Book.class));
	}

}
